package entity

import (
	"bytes"
	"strconv"
	"time"

	"shqsoft.cn/pas3ui/base"
)

//对公存款认定分户情况
type CmBizFee_Divi struct {
	ID   int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	JLID int       `gorm:"column:JLID"` //帐户序号
	DSTY int       `gorm:"column:DSTY"` //分户方式
	EMID int       `gorm:"column:EMID"` //员工序号
	DSVL float64   `gorm:"column:DSVL"` //分户值
	ISWO int       `gorm:"column:ISWO"` //是否删除
	DSEM string    `gorm:"column:DSEM"`
	WOEM string    `gorm:"column:WOEM"`
	OPDT time.Time `gorm:"column:OPDT"`
}

//TableName 对公存款认定分户情况
func (CmBizFee_Divi) TableName() string {
	return "T_CM_BIZ_FEE_DIVI"
}
func CmBizFee_DiviEF() base.EntityFunc {
	return func() interface{} {
		entity := CmBizFee_Divi{}
		return &entity
	}
}
func CmBizFee_DiviESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []CmBizFee_Divi
		return &entities
	}
}

func CmBizFeeDiviBatchSave(acids []int, userNo string, diviMap map[int]float64) (err error) {
	sqlstr := `update "T_CM_BIZ_FEE_DIVI" set "ISWO"= 1,"WOEM"=?,"OPDT"=? where "JLID" in(?)`
	tx := base.MYDB.Begin()
	err = tx.Exec(sqlstr, userNo, time.Now(), acids).Error
	if err != nil {
		tx.Rollback()
		return
	}
	for i := 0; i < len(acids); i++ {
		for k, v := range diviMap {
			divi := CmBizFee_Divi{
				JLID: acids[i],
				EMID: k,
				DSVL: v,
				DSTY: 1,
				ISWO: 0,
				DSEM: userNo,
				OPDT: time.Now(),
			}
			err = tx.Save(&divi).Error
			if err != nil {
				tx.Rollback()
				return
			}
		}
	}
	tx.Commit()
	var buff bytes.Buffer
	buff.WriteString("INSERT INTO JOIN_CM_BIZ_FEE_ISDIVI(JLID,ISRD) ")
	for i, acid := range acids {
		buff.WriteString("SELECT ")
		buff.WriteString(strconv.Itoa(acid))
		buff.WriteString(",1")
		if i < len(acids)-1 {
			buff.WriteString(" UNION ALL ")
		}
	}
	err = base.CHDB.Exec(buff.String()).Error
	if err != nil {
		return err
	}
	return
}

func init() {
	base.DaoPoolObj.Put("CmBizFee_Divi", base.NewDefaultDao(CmBizFee_DiviEF(), CmBizFee_DiviESF(), nil, "my"))
}
